<template>
  <el-dialog :visible="showAllot" title="分配权限" @close="cancelAllot">
    <el-tree
      node-key="id"
      :data="rights"
      default-expand-all
      show-checkbox
      :props="defaultProps"
      :default-checked-keys="currentAllotKeys"
      ref="tree"
    >
    </el-tree>
    <template #footer>
      <el-row type="flex" justify="end">
        <el-button size="small" @click="cancelAllot">取消</el-button>
        <el-button size="small" type="primary" @click="confirmAllot"
          >确定</el-button
        >
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { allotRights, rights } from '@/api/rights'
export default {
  props: {
    showAllot: {
      type: Boolean,
      default: false
    },
    currentId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      rights: [], // 所有权限
      currentAllotKeys: [], // 当前角色权限
      // 树组件配置
      defaultProps: {
        label: 'authName',
        children: 'children'
      }
    }
  },
  async created () {
    this.rights = await rights('tree')
  },
  methods: {
    cancelAllot () {
      this.currentAllotKeys = []
      this.$emit('update:showAllot', false)
    },
    async confirmAllot () {
      try {
        await allotRights({
          id: this.currentId,
          rids: this.$refs.tree.getCheckedKeys().join()
        })
        this.$message.success('分配成功')
        this.$parent.getList()
        this.$emit('update:showAllot', false)
      } catch (err) {
        console.log(err)
      }
    },
    getRightsKeys (data) {
      data.forEach((item) => {
        this.currentAllotKeys.push(item.id)
        if (item?.children?.length) {
          this.getRightsKeys(item.children, this.currentAllotKeys)
        }
      })
    }
  }
}
</script>

<style>
</style>
